import React, {PureComponent, Fragment} from 'react';
import {findDOMNode} from 'react-dom';
import moment from 'moment';
import {connect} from 'dva';
import {
  List,
  Card,
  Row,
  Radio,
  Input,
  Badge,
  Button,
  Icon,
  Dropdown,
  Menu,
  Avatar,
  Modal,
  Form,
  message,
  Select,
  Table,
  Popconfirm,Tag
} from 'antd';

import AddOrEditRole from './addOrEditRole';
import MyPagination from '@/components/MyPagination';
import find from 'lodash/find'
import debounce from 'lodash/debounce'
const FormItem = Form.Item;
const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const SelectOption = Select.Option;
const {Search, TextArea} = Input;

@connect(({roles, loading}) => ({
  roles,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      showAddBtn: find(this.permissions, {name: 'role_add_and_edit'}),
      showdelBtn: find(this.permissions, {name: 'role_delete'}),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      name: '',
      editRecord: {},
      selectedRowKeys: [],
      addOrEdit: false
    };
  }


  componentDidMount() {
    this.setState({
      tableY: document.querySelector('.table-pagination').getBoundingClientRect().top -
      document.querySelector('.custom-small-table').getBoundingClientRect().top - 50
    })
    const {dispatch} = this.props;
    const {
      roles: {pageLoaded, scrollData},
    } = this.props;
    const table = document.querySelector('.ant-table-body')
    if (pageLoaded) {
      setTimeout(function () {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0)

    } else {
      dispatch({
        type: 'Roles/fetch',
        payload: {
          page: 1,
          per_page: 30,
          name: ''
        },
        callback: ()=> {
          const {dispatch} = this.props;
          dispatch({
            type: 'Roles/changeLoaded',
          })
        }
      });
    }
    table.addEventListener('scroll', debounce(this.scroll, 150))
    window.addEventListener('resize', this.resize)
  }

  resize = ()=> {
    this.changeTableY()
  }
  changeTableY = ()=> {
    this.setState({
      tableY: document.querySelector('.table-pagination').getBoundingClientRect().top -
      document.querySelector('.custom-small-table').getBoundingClientRect().top - 50
    })
  }
  scroll = (e)=> {
    const {dispatch} = this.props;
    dispatch({
      type: 'Roles/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop
      },
    })
  }

  componentWillUnmount() {
    console.log('componentWillUnmount')
    window.removeEventListener('resize', this.resize)
    const table = document.querySelector('.ant-table-body')
    if(table){
      table.removeEventListener('scroll', debounce(this.scroll, 150))
    }
  }


  handleSearch = (values, cb) => {
    console.log('handleSearch', values)
    const that = this;
    const {dispatch} = this.props;
    dispatch({
      type: 'Roles/fetch',
      payload: {
        ...values,
      },
      callback: function () {
        that.setState({
          ...values,
        });
        if (cb) cb()
      }
    });
  }

  handleDelete = id => {
    const that = this;
    const {dispatch} = this.props;
    dispatch({
      type: 'Roles/remove',
      payload: {id},
      callback: ()=> {
        message.success('删除角色成功')
        const {
          roles: {searchParams},
        } = that.props;
        that.handleSearch(searchParams);
      }
    });
  };

  renderSimpleForm() {
    const {
      form: {getFieldDecorator},
      roles: {searchParams},
    } = this.props;
    return (
      <Form layout="inline" className="search-form">
        <FormItem label="角色">
          {getFieldDecorator('username', {
            initialValue: searchParams.username,
          })(<Input placeholder="请输入"/>)}
        </FormItem>
        <FormItem >
          <Button type="primary" icon='search' onClick={()=> {
            const {form} = this.props;
            form.validateFields((err, fieldsValue) => {
              if (err) return;

              const values = {
                ...fieldsValue,
              };
              this.handleSearch({
                page: 1,
                per_page: searchParams.per_page,
                username: values.username ? values.username : '',
              })

            });
          }}>
            查询
          </Button>
          <Button style={{marginLeft: 8}} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
          {
            this.state.showAddBtn &&
            <Button icon="plus" style={{marginLeft: 8}} type="primary" onClick={
              ()=> {
                this.setState({
                  editRecord:null,
                  addOrEdit: true
                })
              }
            }>
              新建角色
            </Button>
          }

        </FormItem>

      </Form>
    );
  }

  handleFormReset = () => {
    const {form} = this.props;
    form.resetFields();
    this.handleSearch({
      page: 1,
      username: '',
      per_page: 30
    })
  }
  findChildFunc = (cb)=> {
    this.findChildGroup = cb
  }
  handleAddOrEdit = ()=> {
    const formValues = this.EditRole.props.form.getFieldsValue();
    const permissions = this.findChildGroup()
    const that = this;
    this.props.dispatch({
      type: this.state.editRecord?'Roles/edit':'Roles/add',
      payload: {
        id: this.state.editRecord?this.state.editRecord.id:'',
        ...formValues,
        permissions
      },
      callback: function () {
        message.success( that.state.editRecord?'修改角色成功':'新建角色成功')
        that.setState({
          editRecord:null,
          addOrEdit: false
        });
        const {
          roles: {searchParams},
        } = that.props;
        that.handleSearch(searchParams);
      }
    });
  }
  handleEdit = ()=> {
    const formValues = this.EditRole.props.form.getFieldsValue();
    console.log('formValues', formValues)
    const permissions = this.findChildGroup()
    console.log(permissions)
    const that = this;
    this.props.dispatch({
      type: 'Roles/edit',
      payload: {
        ...formValues,
        id: this.state.editRecord.id,
        permissions
      },
      callback: function () {
        message.success('修改角色成功')
        that.setState({
          editModal: false,
        });
        const {
          roles: {searchParams},
        } = that.props;
        that.handleSearch(searchParams);
      }
    });
  }

  render() {
    const {
      roles: {data, loading, meta, selectedRowKeys},
    } = this.props;
    const columns = [
      {
        title: '角色',
        width: 150,
        dataIndex: 'display_name',
        render:(val)=>{
          return  <Tag color="red">{val}</Tag>
        }
      },
      {
        title: '状态',
        dataIndex: 'status',
        width: 80,
        render(val) {
          return val === 1 ? <Fragment> <Icon type="check-circle" theme="twoTone"  className="table-icon" twoToneColor="#52c41a"/>启用</Fragment>:
            <Fragment> <Icon type="close-circle" theme="twoTone" className="table-icon" twoToneColor="#eb2f96"/>禁用</Fragment>
        },
      },
      {
        title: '创建时间',
        dataIndex: 'created_at',
      },
      {
        title: '操作',
        width: 160,
        fixed: 'right',
        render: (text, record) => (
          <Fragment>
            {
              this.state.showAddBtn &&
              <Button type="primary" icon='edit' size="small" onClick={()=> {
                this.setState({
                  editRecord: record,
                  addOrEdit: true
                })
              }
              }>编辑</Button>
            }
            {
              this.state.showdelBtn &&
              <Popconfirm title={'确定要删除吗?'}
                          onConfirm={()=>this.handleDelete(record.id)}>
                <Button icon='delete'
                        size="small" type="danger">删除</Button>
              </Popconfirm>
            }
          </Fragment>
        ),
      },
    ];
    const rowSelection = {
      columnWidth: 40,
      selectedRowKeys,
      columnTitle: ' '
    };

    return !this.state.addOrEdit ? <Fragment>
      <div className="custom-card">
        <div className="table-title">用户组管理</div>
        <div className="table-page">
          <div className="table-condition">{this.renderSimpleForm()}</div>
          <div >
            <Table
              className="custom-small-table"
              loading={loading}
              rowKey={'id'}
              dataSource={data}
              columns={columns}
              pagination={false}
              size="small"
              scroll={{x: true, y: this.state.tableY}}
              rowSelection={rowSelection}
              onRow={(record) => ({
                onClick: () => {
                  this.props.dispatch({
                    type: 'Roles/selectRow',
                    payload: record,
                  })
                },
              })}
            />
          </div>
        </div>
        <div className="table-pagination">
          <MyPagination searchCondition={{username: this.state.username}} meta={meta} handleSearch={this.handleSearch}/>
        </div>
      </div>
    </Fragment> :
      <Fragment>
        <div className="custom-card">
          <div className="table-title"><span className="breadcrumb-click" onClick={()=>{
            this.setState({
              editRecord:null,
              addOrEdit: false
            })
          }}>用户组管理</span> <span className="breadcrumb-icon">></span> {this.state.editRecord?`编辑 ${this.state.editRecord.display_name}`:"新建用户组"}</div>
          <div className="table-page">
              <AddOrEditRole findChildFunc={this.findChildFunc} editRecord={this.state.editRecord}
                             wrappedComponentRef={(inst) => this.EditRole = inst}/>
              <div className="bottom-operate">
                <Button type="dashed" style={{marginRight:'12px'}} onClick={()=>{
                  this.setState({
                    editRecord:null,
                    addOrEdit: false
                  })
                }}>取消</Button>
                <Button type="primary" onClick={this.handleAddOrEdit}>保存</Button>
              </div>
          </div>
        </div>
      </Fragment>
  }
}

export default BasicList;
